package com.zzyl.aop;

import com.zzyl.annotation.HasPermission;
import com.zzyl.constant.UserCacheConstant;
import com.zzyl.dto.LoginDto;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.service.UserService;
import com.zzyl.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import java.util.Set;

@Component
@Aspect
@Slf4j
public class SecurityAop {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();//模糊匹配工具类

    @Before("@annotation(hasPermission)")
    public void beforeAccess(JoinPoint joinPoint, HasPermission hasPermission) throws Throwable {
        //获取用户访问的资源
        String[] perms = hasPermission.perms();
        //获取用户Id
        String userId = UserThreadLocal.getSubject();
        //获取资源列表
        Set<String> allResourceLabelList = stringRedisTemplate.opsForSet().members(UserCacheConstant.USER_RESOURCE_LIST + userId);
        //查验
        boolean flag = false;
        if(!CollectionUtils.isEmpty(allResourceLabelList)){
            for (String label : allResourceLabelList) {
                boolean match = antPathMatcher.match(label, perms[0]);
                if (match) {
                    flag=true;
                    break;
                }
            }
        }
        if(!flag){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
    }
}
